package com.example.peibei.ui.activity;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.dingtao.common.bean.User;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDActivity;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.SPUtils;
import com.dingtao.common.util.SignTool;
import com.dingtao.common.util.StatusBarUtil;
import com.dingtao.common.util.UIUtils;
import com.example.peibei.BuildConfig;
import com.example.peibei.R;
import com.example.peibei.base.Constant;
import com.example.peibei.base.SpConstant;
import com.example.peibei.service.presenter.GetSmsPresenter;
import com.example.peibei.service.presenter.LoginPresenter;
import com.example.peibei.service.presenter.UserInfoPresenter;
import com.example.peibei.service.presenter.UserSigPresenter;
import com.example.peibei.ui.fragment.MeFragment;
import com.example.peibei.ui.utils.LevelImage;
import com.example.peibei.ui.weight.CountDownTimer;
import com.gyf.immersionbar.ImmersionBar;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.qcloud.tuicore.TUILogin;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = Constant.ACTIVITY_URL_LOGIN)
public class LoginActivity extends WDActivity {
    @BindView(R.id.et_phone)
    EditText phone;
    @BindView(R.id.et_sem)
    EditText sms;
    @BindView(R.id.et_tuiguang)
    EditText tuiguang;
    @BindView(R.id.tv_get_sem)
    TextView tv_get_sem;
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @BindView(R.id.ll_tuiguang)
    LinearLayout ll_tuiguang;
    @BindView(R.id.tv_login_tuiguang)
    TextView tv_login_tuiguang;

    private GetSmsPresenter getSmsPresenter;
    private LoginPresenter loginPresenter;
    private UserSigPresenter userSigPresenter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        ImmersionBar.with(this)
                .fitsSystemWindows(false)
                .fullScreen(true)
                .init();
        getSmsPresenter = new GetSmsPresenter(new SmsCall());
        loginPresenter = new LoginPresenter(new LoginCall());
        userSigPresenter = new UserSigPresenter(new UserSigCall());
    }

    @Override
    protected void destoryData() {
        timer.cancel();
    }

    @OnClick(R.id.iv_close_login)
    public void close() {
        finish();
    }

    @OnClick(R.id.tv_login_tuiguang)
    public void tuiguang() {
        if (ll_tuiguang.getVisibility()==View.GONE){
            ll_tuiguang.setVisibility(View.VISIBLE);
            tv_login_tuiguang.setText("验证码登录");
        }else{
            ll_tuiguang.setVisibility(View.GONE);
            tv_login_tuiguang.setText("邀请码登录");
        }

    }

    @OnClick(R.id.tv_login_password)
    public void toLoginPsw() {
        intent(LoginForPasswordActivity.class);
        finish();
    }

    CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            tv_get_sem.setText(millisUntilFinished / 1000 + "秒");
        }

        @Override
        public void onFinish() {
            tv_get_sem.setEnabled(true);
            tv_get_sem.setText("获取");
        }
    };

    @OnClick(R.id.tv_user_Agree)
    public void userAgree() {
        Bundle bundle = new Bundle();
        bundle.putString("type", "userAgree");
        intent(UserAgreeActivity.class, bundle);
    }

    @OnClick(R.id.tv_private_agree)
    public void privateAgree() {
        Bundle bundle = new Bundle();
        bundle.putString("type", "privateAgree");
        intent(UserAgreeActivity.class, bundle);
    }

    private IWXAPI api;
    private static final String APP_ID = "wx4de7acf350b321e9";

    @OnClick(R.id.ll_login_wx)
    public void loginWx() {
        if (!checkbox.isChecked()) {
            hideInput();
            UIUtils.showToastSafe("登录前，请先同意用户协议和隐私政策");
            return;
        }
//         通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, APP_ID, true);
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        api.sendReq(req);
//        getSign();
    }

    private void getSign() {
//        SignTool.printSignatureMD5(LoginActivity.this,"com.example.peibei");
        try {   //BuildConfig.APPLICATION_ID   当前应用包名
            PackageInfo packageInfo = getPackageManager().getPackageInfo(BuildConfig.APPLICATION_ID,
                    PackageManager.GET_SIGNATURES);
            String signValidString = getSignValidString(packageInfo.signatures[0].toByteArray());
            Log.e("获取应用签名", BuildConfig.APPLICATION_ID + ":" + signValidString);
        } catch (Exception e) {
            Log.e("获取应用签名", "异常:" + e);
        }
    }

    private String getSignValidString(byte[] paramArrayOfByte) throws NoSuchAlgorithmException {
        MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
        localMessageDigest.update(paramArrayOfByte);
        return toHexString(localMessageDigest.digest());
    }

    public String toHexString(byte[] paramArrayOfByte) {
        if (paramArrayOfByte == null) {
            return null;
        }
        StringBuilder localStringBuilder = new StringBuilder(2 * paramArrayOfByte.length);
        for (int i = 0; ; i++) {
            if (i >= paramArrayOfByte.length) {
                return localStringBuilder.toString();
            }
            String str = Integer.toString(0xFF & paramArrayOfByte[i], 16);
            if (str.length() == 1) {
                str = "0" + str;
            }
            localStringBuilder.append(str);
        }
    }

    @OnClick(R.id.tv_get_sem)
    public void getSms() {
        String phoneNum = phone.getText().toString();
        if (TextUtils.isEmpty(phoneNum)) {
            UIUtils.showToastSafe("请输入正确的手机号码");
            return;
        }
        if (UIUtils.isChinaPhoneLegal(phoneNum)) {
            getSmsPresenter.reqeust(phoneNum);
        } else {
            UIUtils.showToastSafe("请输入正确的手机号码");
        }
    }

    @OnClick(R.id.bt_login)
    public void login() {
        String phoneNum = phone.getText().toString();
        String smsNum = sms.getText().toString();
        if (!checkbox.isChecked()) {
            hideInput();
            UIUtils.showToastSafe("登录前，请先同意用户协议和隐私政策");
            return;
        }
        if (TextUtils.isEmpty(phoneNum)) {
            UIUtils.showToastSafe("请输入正确的手机号码");
            return;
        }
        if (TextUtils.isEmpty(smsNum)) {
            UIUtils.showToastSafe("验证码不能为空");
            return;
        }
        if (TextUtils.isEmpty(tuiguang.getText())) {
            loginPresenter.reqeust(smsNum, phoneNum, "");
        } else {
            loginPresenter.reqeust(smsNum, phoneNum, tuiguang.getText().toString());
        }

    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    class SmsCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            tv_get_sem.setEnabled(false);
            timer.start();
            UIUtils.showToastSafe("验证码已发送");
        }

        @Override
        public void fail(ApiException e, Object... args) {
            UIUtils.showToastSafe(e.getDisplayMessage());
        }
    }

    class UserSigCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            SPUtils spUtils = new SPUtils(LoginActivity.this, SpConstant.USER_TOKEN);
            spUtils.putString(SpConstant.USER_SIG, data);
            intent(MainActivity.class);
        }

        @Override
        public void fail(ApiException e, Object... args) {

        }
    }

    class LoginCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            UIUtils.showToastSafe("登录成功");
            if (!TextUtils.isEmpty(data)) {
                SPUtils spUtils = new SPUtils(LoginActivity.this, SpConstant.USER_TOKEN);
                spUtils.putString(SpConstant.USER_TOKEN, data);
                userSigPresenter.reqeust("Bearer " + data);
            }
        }

        @Override
        public void fail(ApiException e, Object... args) {
            UIUtils.showToastSafe(e.getDisplayMessage());
        }
    }
}
